/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode convertBST(TreeNode root) {
        convertToList(root);
        int sum = 0;
        for (int i = list.size() - 1; i >= 0; i--) {
            TreeNode curr = list.get(i);
            sum += curr.val;
            curr.val = sum;
        }
        return root;
    }
    private void convertToList(TreeNode root) {
        if (root == null) {
            return;
        }
        convertToList(root.left);
        list.add(root);
        convertToList(root.right);
    }
    private List<TreeNode> list = new ArrayList<>();
}
